#!/bin/env python
#-*- coding:utf8 -*-
'''
Created on 2017年6月7日

@author: smly
'''

from __future__ import division
import memcache

d_percent = {}

class Memcache_mon(object):
    def __init__(self, host, port):
        self.host = host
        self.port = port 
    
    def _conn_memcache(self):
        mem_conn = memcache.Client([str(self.host) + ':' + str(self.port) ], debug=0)
        return mem_conn
    
    def _get_stats(self):
        try:
            mc = self._conn_memcache()
        except:
            print "can't connect memcached!"
        data = mc.get_stats()
        return data
    
    def get_hit_percent(self):
        data = self._get_stats()
        data = data[0][1]
        hit_percent = int(data['get_hits']) / (int(data['get_hits'])+ int(data['get_misses'])) * 100
        hit_percent = '{:.2f}'.format(hit_percent)
        return hit_percent
    
    def _format_percent(self, data, hit_key, miss_key, d_percent_key, d_var1):
        total_var = int(data[hit_key]) +  int(data[miss_key])
        if int(total_var) == 0:
            d_var1[d_percent_key] = 0
        else:
            d_var1[d_percent_key] = int(data[hit_key]) / int(total_var) * 100
        return d_var1[d_percent_key]     
    
    def _hit_percents(self):
        data = self._get_stats()
        data = data[0][1]
        self._format_percent(data, 'get_hits', 'get_misses', 'get_hit_percent', d_percent)
        self._format_percent(data, 'delete_hits', 'delete_misses', 'delete_hit_percent', d_percent)
        self._format_percent(data, 'cas_hits', 'cas_misses', 'cas_hit_percent', d_percent)
        self._format_percent(data, 'incr_hits', 'incr_misses', 'incr_hit_percent', d_percent)
        self._format_percent(data, 'decr_hits', 'decr_misses', 'decr_hit_percent', d_percent)
        return d_percent
    
if __name__ == '__main__':
    host = '127.0.0.1'
    port = 11211
    mc = Memcache_mon(host, port)
#     ms = mc._get_stats()[0][1].keys()
#     data = mc._get_stats()
#     print data[0][1].keys()
    #hit_percent = mc.get_hit_percent()
#     print 'memcache get hit percent is: %s%%' % hit_percent
    print mc._hit_percents()